0-1 Knapsack Algorithm
The 0-1 Knapsack Algorithm is a classic optimization problem in computer science and combinatorics, where the goal is to determine the most valuable combination of items to include in a knapsack without exceeding its weight capacity. Given a set of items, each with a weight and a value, the algorithm aims to maximize the total value of the items placed in the knapsack while ensuring that the total weight does not exceed the knapsack's limit. The 0-1 nature of the problem refers to the fact that each item can either be included or excluded from the knapsack, without any fractional parts or repetitions.
To solve the 0-1 Knapsack Problem, dynamic programming is often used as it breaks the problem down into smaller overlapping subproblems and builds a solution from the bottom up. The algorithm constructs a table with rows representing the items and columns representing the possible weight capacities of the knapsack. Each cell in the table holds the maximum value that can be achieved using the current set of items and the current weight capacity. The final solution can be found in the bottom-right cell of the table, representing the maximum value that can be achieved using all the items and the full capacity of the knapsack. The 0-1 Knapsack Algorithm is widely used in various fields such as finance, logistics, and resource allocation due to its effectiveness in solving complex optimization problems.
/*
Petar 'PetarV' Velickovic
Algorithm: 0/1 Knapsack
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
using namespace std;
typedef long long lld;
int n, capacity;
int Weight[101], Value[101], Sol[1001];
//Algoritam za odredjivanje maksimalne vrednosti koja moze stati u ranac datog kapaciteta
//Mozemo uzeti tacno jedan komad od svake vrste predmeta
//Slozenost O(n*K)
inline int Knapsack01()
{
for (int i=0;i<=capacity;i++) Sol[i] = 0;
for (int i=0;i<n;i++)
{
for (int j=capacity;j>=1;j--)
{
if (Weight[i] <= j)
{
int x = Sol[j];
int y = Sol[j-Weight[i]]+Value[i];
Sol[j] = max(x,y);
}
}
}
return Sol[capacity];
}
int main()
{
n = 4, capacity = 6;
Weight[0] = 1, Value[0] = 4;
Weight[1] = 2, Value[1] = 6;
Weight[2] = 3, Value[2] = 12;
Weight[3] = 2, Value[3] = 7;
printf("%d\n",Knapsack01());
return 0;
}